<template>
  <div class="p-6 max-w-4xl mx-auto">
    <h1 class="text-2xl font-bold mb-6">{{ $t('common.settings') }}</h1>

    <!-- 标签页导航 -->
    <div class="border-b border-gray-200 mb-6">
      <TabsRoot v-model="activeTab" class="w-full">
        <TabsList class="flex">
          <TabsTrigger
            value="general"
            class="px-4 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 border-b-2 border-transparent data-[state=active]:border-indigo-500 data-[state=active]:text-indigo-600"
          >
            {{ $t('common.language') }}
          </TabsTrigger>
          <TabsTrigger
            value="models"
            class="px-4 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 border-b-2 border-transparent data-[state=active]:border-indigo-500 data-[state=active]:text-indigo-600"
          >
            模型设置
          </TabsTrigger>
        </TabsList>

        <!-- 通用设置内容 -->
        <TabsContent value="general" class="mt-4">
          <div class="bg-white rounded-lg shadow p-6 mb-6">
            <h2 class="text-xl font-semibold mb-4">{{ $t('settings.languageSettings') }}</h2>

            <div class="flex items-center gap-4 mb-2">
              <span class="text-gray-700 w-32">{{ $t('settings.currentLanguage') }}:</span>
              <SelectRoot v-model="language" class="relative">
                <SelectTrigger
                  class="inline-flex items-center justify-between rounded px-4 py-2 text-sm gap-1 bg-white border border-gray-300 hover:bg-gray-50 data-[state=open]:bg-gray-50 outline-none min-w-[180px]"
                >
                  <SelectValue :placeholder="$t('settings.selectLanguage')">
                    {{ getCurrentLanguageLabel() }}
                  </SelectValue>
                </SelectTrigger>

                <SelectPortal>
                  <SelectContent
                    class="overflow-hidden bg-white rounded-md shadow-md border border-gray-200 min-w-[180px]"
                    position="popper"
                  >
                    <SelectViewport class="p-1">
                      <SelectGroup>
                        <SelectLabel class="px-6 text-xs text-gray-500 py-2">
                          {{ $t('settings.selectLanguage') }}
                        </SelectLabel>
                        <SelectItem
                          v-for="option in languageOptions"
                          :key="option.value"
                          :value="option.value"
                          class="relative flex items-center h-8 px-6 rounded text-sm hover:bg-gray-100 outline-none data-[highlighted]:bg-gray-100 data-[state=checked]:bg-gray-100"
                        >
                          <SelectItemIndicator
                            class="absolute left-0 w-6 inline-flex items-center justify-center"
                          >
                            <svg
                              xmlns="http://www.w3.org/2000/svg"
                              width="16"
                              height="16"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              stroke-linecap="round"
                              stroke-linejoin="round"
                            >
                              <path d="M20 6 9 17l-5-5" />
                            </svg>
                          </SelectItemIndicator>
                          <SelectItemText>{{ option.label }}</SelectItemText>
                        </SelectItem>
                      </SelectGroup>
                    </SelectViewport>
                  </SelectContent>
                </SelectPortal>
              </SelectRoot>
            </div>

            <p class="text-sm text-gray-500 mt-2">
              {{ $t('settings.currentLanguage') }}: {{ getCurrentLanguageLabel() }}
            </p>
          </div>
        </TabsContent>

        <!-- 模型设置内容 -->
        <TabsContent value="models" class="mt-4">
          <div class="bg-white rounded-lg shadow p-6 mb-6">
            <!-- 动态生成AI提供商配置表单 -->
            <div v-for="provider in providerList" :key="provider.id" class="mb-4">
              <CollapsibleRoot>
                <CollapsibleTrigger
                  class="flex items-center justify-between w-full p-3 bg-gray-50 rounded-md hover:bg-gray-100 transition-colors"
                >
                  <div class="flex items-center">
                    <div
                      class="w-8 h-8 flex items-center justify-center bg-gray-200 rounded-full mr-2 overflow-hidden"
                    >
                      <img
                        v-if="provider.avatar"
                        :src="provider.avatar"
                        :alt="provider.title"
                        class="w-full h-full object-cover"
                      />
                    </div>
                    <span class="font-medium">{{ provider.title }}</span>
                  </div>
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    class="transform transition-transform duration-200"
                  >
                    <path d="m6 9 6 6 6-6" />
                  </svg>
                </CollapsibleTrigger>
                <CollapsibleContent class="p-4 border border-gray-200 rounded-md mt-2">
                  <!-- 使用动态表单组件 -->
                  <ProviderConfigForm :provider-name="provider.name" @saved="handleConfigSaved" />
                </CollapsibleContent>
              </CollapsibleRoot>
            </div>
          </div>
        </TabsContent>
      </TabsRoot>
    </div>

    <!-- 底部按钮 -->
    <div class="flex justify-end space-x-4">
      <button
        class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
      >
        {{ $t('common.cancel') }}
      </button>
      <button
        @click="saveAllConfigs"
        class="px-4 py-2 bg-indigo-600 border border-transparent rounded-md text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
      >
        {{ $t('common.save') }}
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, watch, ref, onMounted } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { currentLanguage } from '../i18n'
  import { providerList } from '../testData'
  import ProviderConfigForm from '../components/ProviderConfigForm.vue'
  import useProviderConfigStore from '../store/modules/providerConfigStore'
  import {
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectItemIndicator,
    SelectItemText,
    SelectLabel,
    SelectPortal,
    SelectRoot,
    SelectTrigger,
    SelectValue,
    SelectViewport,
    TabsContent,
    TabsList,
    TabsRoot,
    TabsTrigger,
    CollapsibleContent,
    CollapsibleRoot,
    CollapsibleTrigger
  } from 'radix-vue'

  // 使用i18n
  const { t } = useI18n()

  // 当前激活的标签页
  const activeTab = ref('general')

  // 语言选项 - 固定显示各自的语言名称
  const languageOptions = [
    { value: 'zh', label: '中文' },
    { value: 'en', label: 'English' }
  ]

  // 当前选择的语言，使用响应式引用
  const language = computed({
    get: () => currentLanguage.value,
    set: value => {
      console.log('切换语言:', value) // 添加调试日志
      currentLanguage.value = value
      // 强制更新语言标签
      setTimeout(() => {
        console.log('当前语言已更新为:', currentLanguage.value)
      }, 0)
    }
  })

  // 监听语言变化，确保UI更新
  watch(
    () => currentLanguage.value,
    newLang => {
      console.log('语言已变更，触发watch:', newLang)
    }
  )

  // 获取当前语言的显示名称
  const getCurrentLanguageLabel = () => {
    console.log('获取当前语言标签，当前语言为:', language.value)
    const option = languageOptions.find(opt => opt.value === language.value)
    return option ? option.label : ''
  }

  // 获取配置store
  const providerConfigStore = useProviderConfigStore()

  // 初始化配置
  onMounted(() => {
    providerConfigStore.initConfig()
  })

  // 处理配置保存成功
  const handleConfigSaved = () => {
    // 可以在这里添加提示信息
    console.log('配置已保存')
  }

  // 保存所有配置
  const saveAllConfigs = () => {
    // 保存到localStorage
    providerConfigStore.saveToLocalStorage()
    console.log('所有配置已保存')
  }
</script>

<style scoped></style>
